<?php
/**
 * Created by PhpStorm.
 * User: zhendong
 * Date: 2017/4/18
 * Time: 18:29
 */
namespace Backend\Controller;
use Think\Controller;

class AdDeliveryController extends BaseController
{

    //初始化变量
    protected $ad_delivery_model;
    protected $ad_order_model;
    protected $code_model;
    protected $ad_model;
    protected $ad_delivery_set_model;
    protected $media_model;

    public function __construct() {
        parent::__construct();
        $this->ad_delivery_set_model = D('AdDeliverySet');
        $this->ad_delivery_model     = D('AdDelivery');
        $this->ad_order_model        = D('AdOrder');
        $this->code_model            = D('Code');
        $this->media_model           = D('Media');
        $this->ad_model              = D('Ad');

    }

    public function index() {
        $num = !empty(I('get.n')) ? I('get.n') : C('USER_DEFINED_CONF.PAGE_LIST_ROWS');     //每页显示的条数
        $key = !empty(I('get.k')) ? I('get.k') : '';    //每页显示的条数

        $ids = rtrim(I('get.ids'), ',');
        if (!empty($ids)) {
            $condition['d.id'] = array('in', $ids);
        } else {
            $condition = [];
        }

        $data = $this->ad_delivery_model->get_ad_delivery_join_data($condition, $num);

        $this->assign('page', $data['page']);
        $this->assign('lists', $data['data']);
        $this->display();
    }

    public function add() {
        if(IS_POST) {
            $data = $_POST;

            $data['start_time']         = !empty($data['start_time']) ? strtotime($data['start_time']) : '';
            $data['end_time']           = !empty($data['end_time']) ? strtotime($data['end_time']) : '';
            $data['interval_time']      = !empty($data['interval_time']) ? $this->getFormatDate($data['interval_time']) : '';
            $data['ad_id']              = trim($data['ad_id'], ',');
            //定义范围【add】
            $ad_delivery_add_data_range = [
                'order_id',
                'ad_name',
                'sale_mode',
                'billing_mode',
                'price',
                'carrier_type',
                'code_id',
                'ad_id'
            ];

            $data = $this->ad_delivery_model->get_ad_delivery_data_format($ad_delivery_add_data_range,$data);
            $data = $this->ad_delivery_model->get_delivery_state($data);

            if(!$this->ad_delivery_model->create($data['0'])) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => $this->ad_delivery_model->getError()]);
            } else {

                if(!$this->ad_delivery_set_model->create($data['1'])) {
                    $this->ajaxReturn(['status' => 'failed', 'msg' => $this->ad_delivery_set_model->getError()]);
                }

                $this->checkTimeSet($data);

                $result = $this->ad_delivery_model->filter('htmlspecialchars')->add($data['0']);
                if($result !== false) {

                    $insertId = $result;
                    $data['1']['delivery_id'] = $insertId;
                    $res= $this->ad_delivery_set_model->filter('htmlspecialchars')->add($data['1']);

                    if($res !== false) {
                        $this->ajaxReturn(['status' => 'success', 'msg' => '创建成功！']);
                    } else {
                        $this->ajaxReturn(['status' => 'failed', 'msg' => '创建失败！']);
                    }

                } else {
                    $this->ajaxReturn(['status' => 'failed', 'msg' => '创建失败！']);
                }
            }

        } else {

            $ad_order_lists = $this->ad_order_model->get_ad_order_info();   //获取广告订单信息
            $media          = $this->media_model->field('id, name')->order('id desc')->select();
            $ad_lists       = $this->ad_model->field('id, ad_name')->select();

            $this->assign('media', $media);
            $this->assign('orders', $ad_order_lists);
            $this->assign('ads', $ad_lists);
            $this->display();
        }
    }

    public function edit() {
        if(IS_POST) {
            $data = $_POST;
            $data['start_time']         = !empty($data['start_time']) ? strtotime($data['start_time']) : '';
            $data['end_time']           = !empty($data['end_time']) ? strtotime($data['end_time']) : '';
            $data['interval_time']      = !empty($data['interval_time']) ? $this->getFormatDate($data['interval_time']) : '';
            $data['ad_id']              = trim($data['ad_id'], ',');
            //定义范围【edit】
            $ad_delivery_edit_data_range = [
                'id',
                'order_id',
                'ad_name',
                'sale_mode',
                'billing_mode',
                'price',
                'carrier_type',
                'code_id',
                'ad_id'
            ];

            $data = $this->ad_delivery_model->get_ad_delivery_data_format($ad_delivery_edit_data_range,$data);
            $data = $this->ad_delivery_model->get_delivery_state($data);
            $condition = ['delivery_id' => $data['0']['id']];

            if(!$this->ad_delivery_model->create($data['0'])) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => $this->ad_delivery_model->getError()]);
            } else {

                if(!$this->ad_delivery_set_model->create($data['1'])) {
                    $this->ajaxReturn(['status' => 'failed', 'msg' => $this->ad_delivery_set_model->getError()]);
                }

                $this->checkTimeSet($data);

                if(($this->ad_delivery_model->filter('htmlspecialchars')->save($data['0']) !== false) && ($this->ad_delivery_set_model->where($condition)->filter('htmlspecialchars')->save($data['1']) !== false) ) {
                    $this->ajaxReturn(['status' => 'success', 'msg' => '修改成功！' ]);
                } else {
                    $this->ajaxReturn(['status' => 'failed', 'msg' => '修改失败！' ]);
                }
            }
        } else {

            $id = I('get.id');
            $where = ['d.id' => $id];

            $list = $this->ad_delivery_model->get_ad_delivery_join_find($where);
            $code_lists = $this->code_model->get_code_info();               //获取代码位信息
            $ads = explode(',', $list['d_ad_id']);
            $map_in['id']   = array('IN', $ads);
            $map_not['id']  = array('NOT IN', $ads);

            $ad_lists       = $this->ad_model->field('*')->where($map_in)->select();               //获取物料信息
            $ad_lists_not   = $this->ad_model->field('id,ad_name')->where($map_not)->select();
            $media          = $this->media_model->field('id,name')->order('id desc')->select();
            $code           = $this->code_model->field('id,code_name')->where('id', $list['code_id'])->select();

            $this->assign('code', $code);
            $this->assign('media', $media);
            $this->assign('list', $list);
            $this->assign('codes', $code_lists);
            $this->assign('ads', $ad_lists);
            $this->assign('ads_not', $ad_lists_not);
            $this->display();
        }
    }

    public function update() {

    }

    public function delete() {
        $id = I('post.id');
        if($this->ad_delivery_model->delete($id) && $this->ad_delivery_set_model->where(['delivery_id' => $id])->delete()) {
            $this->ajaxReturn(['status' => 'success', 'msg' => '操作成功！']);
        } else {
            $this->ajaxReturn(['status' => 'failed', 'msg' =>'操作失败！']);
        }
    }

    /**
     * 物料列表
     */
    public function ad_lists() {
        $ad_lists = $this->ad_model->get_ad();
        $this->assign('page', $ad_lists['page']);
        $this->assign('ad_lists', $ad_lists['data']);
        $this->display();
    }

    /**
     * 检查时间设置
     * @param array $data
     */
    public function checkTimeSet($data = []) {
        //判断时间设置
        if ($data['1']['delivery_time_set'] == 1) { //连续时间设定

            if (empty($data['1']['start_time'])) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => '请设定广告投放开始时间!']);
            }

            if ($data['1']['end_time_set'] == 1 && empty($data['1']['end_time'])) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => '请设定广告投放结束时间!']);
            }

            if (!empty($data['1']['end_time']) && ($data['1']['end_time'] <= $data['1']['start_time'] + 86400) ) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => '设定广告投放时间段间隔最少为1天！']);
            }
        } elseif ($data['1']['delivery_time_set'] == 2) {   //不连续时间设定
            if (empty($data['1']['interval_time'])) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => '请设定广告投放不连续时间!']);
            }
        } else {
            $this->ajaxReturn(['status' => 'failed', 'msg' => '投放时间状态码异常！']);
        }
    }

}